const { Schema, SchemaTypes } = require('../schema');
const timeTool = require('../../module/tool/time');
const mongoose = require('mongoose');
const SourceType = require('../../module/const/IncomeSource');
class TaskIncome extends Schema {
    PropertyModelDataTemplate () {
        return {
            adminId: {
                type: SchemaTypes.ObjectId,
                required: true
            },
            areaId: {
                type: SchemaTypes.ObjectId,
                required: false
            },
            orderId: {
                type: SchemaTypes.ObjectId,
                required: true
            },
            price: {
                type: SchemaTypes.Number,
                required: true
            },

            description: {
                type: SchemaTypes.String,
                required: false
            },
            createTime: {
                type: SchemaTypes.Number,
                required: true,
                default: timeTool.getCurrentTimestamp()
            },
            isAbandoned: {
                type: SchemaTypes.Boolean,
                required: true,
                default: false
            },

            source: {
                type: SchemaTypes.Number,
                required: false,
                default: SourceType.order.value
            }
        };
    }

    async getTaskIncomeAccount (adminId, beginTimeStamp, endTimeStamp) {
        return this.getModel().aggregate([
            {
                $match: {
                    adminId: mongoose.Types.ObjectId(adminId),
                    isAbandoned: false,
                    create_time: {
                        $gte: beginTimeStamp,
                        $lte: endTimeStamp
                    }
                }
            },
            { $group: { _id: null, total: { $sum: '$price' } } }
        ]);
    }

    async getTotalAccount () {
        return this.getModel().aggregate([
            {
                $match: {
                    isAbandoned: false
                }
            },
            { $group: { _id: null, total: { $sum: '$price' } } }
        ]);
    }

    async generateTaskIncome (adminId, price, orderId, description, areaId) {
        if (price > 0) {
            return this.getDoc({
                adminId: adminId,
                price: price,
                areaId: areaId,
                orderId: orderId,
                description: description
            }).save();
        } else {
            return 0;
        }
    }
}

module.exports = TaskIncome;
